package com.ugoodtech.mdcc.client.controller;

import com.drew.lang.StringUtil;
import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.client.controller.ResponseObject.QuestionGroupTemp;
import com.ugoodtech.mdcc.client.dto.GroupResponse;
import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.client.service.QuestionService;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.repository.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(description = "questionTemp")
@RestController
@RequestMapping("/questionTemp")
public class QuestionTempReport {

    private static Logger logger = LoggerFactory.getLogger(QuestionTempReport.class);

    @Autowired
    private StationReportUnFinshedRepository stationReportUnFinshedRepository;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private StationRegularServiceReportUnFinshedRepository stationRegularServiceReportUnFinshedRepository;

    @Autowired
    private StationColorReportTempRepository stationColorReportTempRepository;

    @Autowired
    private StationLeanPaintReportTempRepository stationLeanPaintReportTempRepository;

    @Autowired
    private NationRepository nationRepository;

    @Autowired
    private DepartmentRepository departmentRepository;

    @Autowired
    private ComplaintReportDataTempRepository complaintReportDataTempRepository;

    @Autowired
    private QuestionAnswerOptionRepository questionAnswerOptionRepository;

    private List<StationRegularServiceReportUnFinshed> regularServiceReports = null;
    private List<StationColorReportTemp> colorReports = null;
    private List<StationLeanPaintReportTemp> paintReports = null;
    private List<ComplaintReportDataTemp> complaintReportDataTempList = null;

    @ApiOperation("获取章节分组和题目")
    @RequestMapping(value = "/getGroups", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getGroups(
            Principal principal,
            @ApiParam("章节id") @RequestParam("sectionId") Long sectionId,
            @ApiParam("报告id") @RequestParam("reportId") Long reportId,
            @ApiParam("用户身份") @RequestParam(required = false) Integer owner,
            @ApiParam("报告类型:service_report,techcolor_report,paint_report,complaint_temp_report") @RequestParam(required = false) String reportType
    ) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        logger.info("开始调用此方法");
        Long time = System.currentTimeMillis();
        if (reportId != null && reportId != 0) {
            if (reportType.equals(Constants.SERVICE_REPORT)) {
                regularServiceReports = stationRegularServiceReportUnFinshedRepository.selectAnswer(reportId);
            }
            if (reportType.equals(Constants.TECHCOLOR_REPORT)) {
                colorReports = stationColorReportTempRepository.selectAnswer(reportId);
            }
            if (reportType.equals(Constants.PAINT_REPORT)) {
                paintReports = stationLeanPaintReportTempRepository.selectAnswer(reportId);
            }
            if (reportType.equals(Constants.COMPLAINT_TEMP_REPORT)) {
                complaintReportDataTempList = complaintReportDataTempRepository.selectAnswer(reportId);
            }
        }
        List<QuestionGroup> questionGroups = questionService.getQuestions(sectionId,owner);
//        QuestionGroupTemp questionGroupTemp = new QuestionGroupTemp();
        if (null == complaintReportDataTempList) {
            StationReportTemp stationReportTemp = stationReportUnFinshedRepository.findOne(reportId);
            if (stationReportTemp == null) {

                return JsonResponse.errorResponseWithError("抱歉", "未找到此报告");
            }
            if (stationReportTemp.getSectionId() != null && stationReportTemp.getSectionId() != 0) {
                stationReportTemp.setSectionId(stationReportTemp.getSectionId());
            }
            if (StringUtils.isNotEmpty(stationReportTemp.getAnchor())) {
                stationReportTemp.setAnchor(stationReportTemp.getAnchor());
            } else {
                stationReportTemp.setAnchor("");
            }
        }

        List<Object> data = new ArrayList<>();
        for (QuestionGroup questionGroup : questionGroups) {
            data.add(GroupResponse.turnGroupToResponse(questionGroup));
            List<Question> questionGroupList = questionService.getQuestionsByGroup(questionGroup.getId(),owner);
            for (Question question : questionGroupList) {
                if (null != owner && question.getOwner() != owner && question.getOwner()!=2){
                    continue;
                }
                Long question_id = Long.valueOf(question.getId());
                if (question_id == 146 || question_id == 147 || question_id == 148 || question_id == 149 || question_id == 150 || question_id == 151 ||
                        question_id == 152 || question_id == 153 || question_id == 154) {
                    continue;
                }
                if (reportId != null && reportId != 0) {
                    question = selectAnswer(question, reportId);
                }

                List<QuestionAnswerOption> questionAnswerOptions = questionService.getOptionsByGroup(question.getId(),owner);
                question.setOptions(questionAnswerOptions);
                List<Question> questions = new ArrayList<>();
                questions.add(question);
                if (QuestionCategory.TEXT.equals(question.getCategory())) {
                    Map<String, Object> textQuestion = new HashMap<>();
                    textQuestion.put("category", question.getCategory().name());
                    textQuestion.put("required", Boolean.valueOf(question.getRequired()));
                    textQuestion.put("type", "question");
                    textQuestion.put("inputList", questions);
                    data.add(textQuestion);
                } else {
                    data.add(question);
                }
            }
        }

        QuestionController.In excel = new QuestionController().new In();
        if (sectionId == 10) {
            excel.setExcel(true);
            data.add(excel);
        } else {
            data.add(excel);
        }
        regularServiceReports = null;
        colorReports = null;
        paintReports = null;
        complaintReportDataTempList = null;
        logger.info("调用完毕");
        logger.info("总耗时：" + (System.currentTimeMillis() - time));
        return JsonResponse.successResponseWithData(data);
    }


    private Question selectAnswer(Question question, Long report_id) {
        if (complaintReportDataTempList != null) {
            for (ComplaintReportDataTemp report : complaintReportDataTempList) {
                if (question.getId().equals(report.getQuestionId())) {
                    if (StringUtils.isNotEmpty(report.getAnswerOther())) {
                        question.setAnswer_other(report.getAnswerOther());
                    } else {
                        question.setAnswer_other("");
                    }
                    if (StringUtils.isNotEmpty(report.getAnswerId())) {
                        question.setSelected(report.getAnswerId());
                    } else {
                        question.setSelected("");
                    }
                    if (question.getId().equals(187L)) {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT);
                        question.setAnswer_other(simpleDateFormat.format(new Date()));
                    }
                    if (report.getQuestionId() == 194L) {
                        StringBuffer stringBuffer = new StringBuffer("");
                        if (StringUtils.isNotEmpty(report.getAnswerId())) {
                            String[] ids = report.getAnswerId().split(",");
                            for (String id : ids) {
                                if (StringUtils.isNotEmpty(id)) {
                                    QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                                    if (answerOption != null && StringUtils.isNotEmpty(answerOption.getName())) {
                                        stringBuffer.append(answerOption.getName() + ",");
                                    }
                                }
                            }
                        }
                        if (StringUtils.isNotEmpty(report.getAnswerOther())) {
                            question.setAnswer_other2(report.getAnswerOther());
                        }
                        question.setAnswer_other(stringBuffer.toString());
                    }
                }
            }
            return question;
        }

        if (regularServiceReports != null) {
            for (StationRegularServiceReportUnFinshed report : regularServiceReports) {

                if (question.getId().equals(report.getQuestionId())) {
                    if (StringUtils.isNotEmpty(report.getAnswerOther())) {
                        question.setAnswer_other(report.getAnswerOther());
                    } else {
                        question.setAnswer_other("");
                    }
                    if (report.getQuestionId() == 155L) {
                        QStationReportTemp qStationReport = QStationReportTemp.stationReportTemp;
                        BooleanBuilder builder = new BooleanBuilder();
                        builder.and(qStationReport.deleted.eq(false));
                        builder.and(qStationReport.enabled.eq(true));
                        builder.and(qStationReport.id.eq(report_id));
                        StationReportTemp stationReport = stationReportUnFinshedRepository.findOne(builder);
                        if (stationReport != null && StringUtils.isNotEmpty(stationReport.getAnswerOther())) {
                            question.setAnswer_other2(stationReport.getAnswerOther());
                        }
                    }
                    if (report.getQuestionId() == 156L) {
                        QStationReportTemp qStationReport = QStationReportTemp.stationReportTemp;
                        BooleanBuilder builder = new BooleanBuilder();
                        builder.and(qStationReport.deleted.eq(false));
                        builder.and(qStationReport.enabled.eq(true));
                        builder.and(qStationReport.id.eq(report_id));
                        StationReportTemp stationReport = stationReportUnFinshedRepository.findOne(builder);
                        if (stationReport != null && StringUtils.isNotEmpty(stationReport.getUserIds())) {
                            String[] parentUserIds = stationReport.getUserIds().split(",");
                            StringBuffer stringBuffer = new StringBuffer();
                            for (String id : parentUserIds) {
                                Department department = null;
                                if (StringUtils.isNotEmpty(id)) {
                                    stringBuffer.append((id + ","));
//                                    department = departmentRepository.findOne(Long.valueOf(id));
//                                }
//                                if (department != null) {
//                                    stringBuffer.append((department.getTotalName() + ","));
                                }
                            }
                            question.setAnswer_other(stringBuffer.toString());
                        }
                    }
                    if (StringUtils.isNotEmpty(report.getAnswerPhoto())) {
                        question.setAnswer_photo(report.getAnswerPhoto());
                    } else {
                        question.setAnswer_photo("");
                    }
                    if (StringUtils.isNotEmpty(report.getAnswerId()) && report.getAnswerId().indexOf(",") != -1) {
                        question.setSelected(report.getAnswerId());
                    } else if (StringUtils.isNotEmpty(report.getAnswerId()) && Long.valueOf(report.getAnswerId()) != 0) {
                        question.setSelected(report.getAnswerId());
                    } else {
                        question.setSelected("");
                    }
                }
            }
            return question;
        }

        if (colorReports != null) {
            for (StationColorReportTemp report : colorReports) {
                if (question.getId().equals(report.getQuestionId())) {
                    if (StringUtils.isNotEmpty(report.getAnswerOther())) {
                        question.setAnswer_other(report.getAnswerOther());
                    } else {
                        question.setAnswer_other("");
                    }
                    if (report.getQuestionId() == 173) {
                        if (StringUtils.isNotEmpty(report.getAnswerOther())) {
                            Nation nation = nationRepository.selectByProvince(report.getAnswerOther());
                            if (nation == null) {
                                question.setAnswer_other("");
                            } else {
                                question.setAnswer_other(nation.getProvince());
                            }
                        }
                    }
                    if (report.getQuestionId() == 174) {
                        if (StringUtils.isNotEmpty(report.getAnswerOther())) {
                            List<Nation> nationList = nationRepository.selectByCity(report.getAnswerOther());
                            Nation nation = CollectionUtils.isEmpty(nationList) ? null : nationList.get(0);
                            if (nation == null) {
                                question.setAnswer_other("");
                            } else {
                                question.setAnswer_other(nation.getCity());
                            }
                        }
                    }
                    if (report.getQuestionId() == 8L) {
                        StringBuffer stringBuffer = new StringBuffer("");
                        if (StringUtils.isNotEmpty(report.getAnswerId())) {
                            String[] ids = report.getAnswerId().split(",");
                            for (String id : ids) {
                                if (StringUtils.isNotEmpty(id)) {
                                    QuestionAnswerOption answerOption = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                                    if (answerOption != null && StringUtils.isNotEmpty(answerOption.getName())) {
                                        stringBuffer.append(answerOption.getName() + ",");
                                    }
                                }
                            }
                        }
                        if (StringUtils.isNotEmpty(report.getAnswerOther())) {
                            question.setAnswer_other2(report.getAnswerOther());
                        }
                        question.setAnswer_other(stringBuffer.toString());
                    }
                    if (StringUtils.isNotEmpty(report.getAnswerPhoto())) {
                        question.setAnswer_photo(report.getAnswerPhoto());
                    } else {
                        question.setAnswer_photo("");
                    }
                    if (report.getAnswerId() != null && report.getAnswerId().indexOf(",") != -1) {
                        question.setSelected(report.getAnswerId());
                    } else if (StringUtils.isNotEmpty(report.getAnswerId()) && Long.valueOf(report.getAnswerId()) != 0) {
                        question.setSelected(report.getAnswerId());
                    } else {
                        question.setSelected("");
                    }
                }
            }
            return question;
        }

        if (paintReports != null) {
            for (StationLeanPaintReportTemp report : paintReports) {
                if (question.getId().equals(report.getQuestionId())) {
                    if (StringUtils.isNotEmpty(report.getAnswerOther())) {
                        question.setAnswer_other(report.getAnswerOther());
                    } else {
                        question.setAnswer_other("");
                    }
                    if (StringUtils.isNotEmpty(report.getAnswerPhoto())) {
                        question.setAnswer_photo(report.getAnswerPhoto());
                    } else {
                        question.setAnswer_photo("");
                    }
                    if (report.getAnswerId() != null && report.getAnswerId().indexOf(",") != -1) {
                        question.setSelected(report.getAnswerId());
                    } else if (StringUtils.isNotEmpty(report.getAnswerId()) && Long.valueOf(report.getAnswerId()) != 0) {
                        question.setSelected(report.getAnswerId());
                    } else {
                        question.setSelected("");
                    }
                }
            }
            return question;
        }
        return question;
    }

}
